package com.kingsoft.labs.tangram.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.*;

import com.kingsoft.labs.tangram.blocks.Block;
import com.kingsoft.labs.tangram.domain.Result;
import com.kingsoft.labs.tangram.domain.Task;
import com.kingsoft.labs.tangram.domain.Task.TaskType;
import com.kingsoft.labs.tangram.util.AppContext;
import com.kingsoft.labs.tangram.util.http.HttpHelper;

@SuppressWarnings("serial")
public class ServletService extends HttpServlet implements Service {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		// Build a task

		Map<String, String> args = HttpHelper.parseParam(req.getQueryString());
		Result result = null;
		TaskType type;
		try {
			type = TaskType.valueOf(args.get("type").toUpperCase());
			System.out.println(type);
		} catch (Exception e) {
			PrintWriter writer = resp.getWriter();
			result = new Result();
			result.setAllFlags(false);
			writer.println(result.serialize());
			writer.close();
			return;
		}

		Task task = new Task();
		task.type = type;
		task.is = req.getInputStream();
		task.os = resp.getOutputStream();
		
		switch (type) {
		case WRITE:
			result = processWrite(task);
			break;
		}
		
		task.is.close();
		task.os.write(result.serialize().getBytes());
		task.os.close();
	}
	
	public Result processWrite(Task task) {
		Block root = (Block)AppContext.get().getBean("root");
		Result result = root.doTask(task);
		return result;
	}

	@Override
	public boolean start() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
	
	public static void main(String[] args) {
	}
}
